package com.scenic.rd_android.basic_knowledge;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;

import com.jaredrummler.android.processes.ProcessManager;
import com.jaredrummler.android.processes.models.AndroidAppProcess;
import com.scenic.rd_android.R;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class ShowTaskInfo extends AppCompatActivity {


    final Runnable r = new Runnable() {
        @Override
        public void run() {
//            System.out.println(getActivitiesByApplication(getApplication()));
//            System.out.println(getTaskInfos1(getApplicationContext()));
            testTask2();


        }
    };

    Handler handler = new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_task_info);





       new Thread(new Runnable() {
           @Override
           public void run() {

               while (true){
                   try {
                       Thread.sleep(100);
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
                   handler.post(r);
               }
           }
       }).start();
    }




    private static List<Activity> getActivitiesByApplication(Application application) {
        List<Activity> list = new ArrayList<>();
        try {
            Class<Application> applicationClass = Application.class;
            Field mLoadedApkField = applicationClass.getDeclaredField("mLoadedApk");
            mLoadedApkField.setAccessible(true);
            Object mLoadedApk = mLoadedApkField.get(application);
            Class<?> mLoadedApkClass = mLoadedApk.getClass();
            Field mActivityThreadField = mLoadedApkClass.getDeclaredField("mActivityThread");
            mActivityThreadField.setAccessible(true);
            Object mActivityThread = mActivityThreadField.get(mLoadedApk);
            Class<?> mActivityThreadClass = mActivityThread.getClass();
            Field mActivitiesField = mActivityThreadClass.getDeclaredField("mActivities");
            mActivitiesField.setAccessible(true);
            Object mActivities = mActivitiesField.get(mActivityThread);
            // 注意这里一定写成Map，低版本这里用的是HashMap，高版本用的是ArrayMap
            if (mActivities instanceof Map) {
                @SuppressWarnings("unchecked")
                Map<Object, Object> arrayMap = (Map<Object, Object>) mActivities;
                for (Map.Entry<Object, Object> entry : arrayMap.entrySet()) {
                    Object value = entry.getValue();
                    Class<?> activityClientRecordClass = value.getClass();
                    Field activityField = activityClientRecordClass.getDeclaredField("activity");
                    activityField.setAccessible(true);
                    Object o = activityField.get(value);
                    list.add((Activity) o);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            list = null;
        }
        return list;
    }


    public void testTask2 (){
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.AppTask> tasks = activityManager.getAppTasks();
        System.out.println("tasks length is " + tasks.size());

        for (int i = 0; i < tasks.size(); i++) {

            ActivityManager.RecentTaskInfo taskInfo = tasks.get(i).getTaskInfo();

            System.out.println(taskInfo.topActivity);

        }
    }


    //这是一个实体类,就是描述应用的一些信息
    public  static  class TaskInfo {

        // 应用程序的图标
        private Drawable icon;
        // 应用程序的名字
        private String name;
        // 应用程序的包名
        private String packname;
        // 占用内存的大小
        private long memsize;
        // true 用户进程 false 系统进程
        private boolean userTask;

        //是否已经勾选
        private boolean  cbchecked;

        public boolean isCbchecked() {
            return cbchecked;
        }

        public void setCbchecked(boolean cbchecked) {
            this.cbchecked = cbchecked;
        }

        public Drawable getIcon() {
            return icon;
        }

        public void setIcon(Drawable icon) {
            this.icon = icon;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getPackname() {
            return packname;
        }

        public void setPackname(String packname) {
            this.packname = packname;
        }

        public long getMemsize() {
            return memsize;
        }

        public void setMemsize(long memsize) {
            this.memsize = memsize;
        }

        public boolean isUserTask() {
            return userTask;
        }

        public void setUserTask(boolean userTask) {
            this.userTask = userTask;
        }

        @Override
        public String toString() {
            return "TaskInfo [icon=" + icon + ", name=" + name + ", packname="
                    + packname + ", memsize=" + memsize + ", userTask=" + userTask
                    + "]";
        }

    }

    /**
     * 获取系统运行的进程信息
     *
     * @param context
     * @return
     */
    public static List<TaskInfo> getTaskInfos1(Context context) {
        // 应用程序管理器
        ActivityManager am = (ActivityManager) context
                .getSystemService(context.ACTIVITY_SERVICE);

        // 应用程序包管理器
        PackageManager pm = context.getPackageManager();

        // 获取正在运行的程序信息, 就是以下粗体的这句代码,获取系统运行的进程     要使用这个方法，需要加载
//　import com.jaredrummler.android.processes.ProcessManager;
//　import com.jaredrummler.android.processes.models.AndroidAppProcess;  这两个包, 这两个包附件可以下载
        List<AndroidAppProcess> processInfos = ProcessManager.getRunningAppProcesses();

        List<TaskInfo> taskinfos = new ArrayList<TaskInfo>();
        // 遍历运行的程序,并且获取其中的信息
        for (AndroidAppProcess processInfo : processInfos) {
            TaskInfo taskinfo = new TaskInfo();
            // 应用程序的包名
            String packname = processInfo.name;
            taskinfo.setPackname(packname);
            // 湖区应用程序的内存 信息
            android.os.Debug.MemoryInfo[] memoryInfos = am
                    .getProcessMemoryInfo(new int[] { processInfo.pid });
            long memsize = memoryInfos[0].getTotalPrivateDirty() * 1024L;
            taskinfo.setMemsize(memsize);
            try {
                // 获取应用程序信息
                ApplicationInfo applicationInfo = pm.getApplicationInfo(
                        packname, 0);
                Drawable icon = applicationInfo.loadIcon(pm);
                taskinfo.setIcon(icon);
                String name = applicationInfo.loadLabel(pm).toString();
                taskinfo.setName(name);
                if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                    // 用户进程
                    taskinfo.setUserTask(true);
                } else {
                    // 系统进程
                    taskinfo.setUserTask(false);
                }
            } catch (PackageManager.NameNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                // 系统内核进程 没有名称
                taskinfo.setName(packname);
//                Drawable icon = context.getResources().getDrawable(
//                        R.drawable.default_icon);
//                taskinfo.setIcon(icon);
            }
            if (taskinfo != null) {
                taskinfos.add(taskinfo);
            }
        }
        return taskinfos;
    }

}
